package com.hhxyjsj.email;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class MailHandler {
    //create table addresser(id int auto_increment primary key,mailurl varchar(500),mailaddr varchar(50),password varchar(50),isused char(1),usedate varchar(10));		
	
	/**
	 * 获得数据库连接
	 * @return
	 */
	public static Connection getConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			StringBuffer url = new StringBuffer();
			url.append("jdbc:mysql://")
			   .append(MailUtils.getDbHost())
			   .append(":")
			   .append(MailUtils.getDbPort())
			   .append("/")
			   .append(MailUtils.getDbName());
			Connection conn = DriverManager.getConnection(url.toString(),MailUtils.getDbUserName(),MailUtils.getDbPassword());
			return conn;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 随机查找指条数的收件人
	 * @return
	 */
	private List<String> findAddressee(){
		Connection conn = getConnection();
		List<String> rvt = new ArrayList();
		String sql = "select mail from usermail order by rand() limit " + MailUtils.getRandomNum();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				rvt.add(rs.getString("mail"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			closeObject(conn, ps, rs);
		}
		return rvt;
	}
	/**
	 * 添加发件人信息
	 * @param mailUrl
	 * @param userName
	 * @param password
	 * @return
	 */
	public boolean addAddresser(String mailUrl,String userName,String password){
		Connection conn = getConnection();
		List<String> rvt = new ArrayList();
		String sql = "insert into addresser(mailurl,mailaddr,password,isused) values(?,?,?,?)";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, mailUrl);
			ps.setString(2, userName);
			ps.setString(3, password);
			ps.setString(4, "0");//未使用
			return ps.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			closeObject(conn, ps, null);
		}
		return false;
	}
	/**
	 * 更新所有发件人的使用状态
	 * @return
	 */
	public boolean updateIsUsed(){
		Connection conn = getConnection();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<String> rvt = new ArrayList();
		String sql = "update addresser t set t.isused=?,usedate=? where t.isused=? or (t.isused=? and usedate!=?)";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, Constants.ISUSED_0);
			ps.setString(2, "");
			ps.setString(3, Constants.ISUSED_1);
			ps.setString(4, Constants.ISUSED_2);
			ps.setString(5, sdf.format(new Date()));
			return ps.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			closeObject(conn, ps, null);
		}
		return false;
	}
	/**
	 * 根据发件人更新发件人的使用状态
	 * @param mailAddr
	 * @return
	 */
	public boolean updateIsUsed(String mailAddr,String isUsed){
		Connection conn = getConnection();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<String> rvt = new ArrayList();
		String sql = "update addresser t set t.isused=?,usedate=? where t.mailaddr=?";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, isUsed);//未使用
			ps.setString(2, sdf.format(new Date()));
			ps.setString(3, mailAddr);//未使用
			return ps.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			closeObject(conn, ps, null);
		}
		return false;
	}
	
	/**
	 * 查找所有的发件人地址
	 * @return
	 */
	public List<Map<String,String>> findAddressers(){
		List<Map<String,String>> rvt = new ArrayList<Map<String,String>>();
		Connection conn = getConnection();
		String sql = "select mailurl,mailaddr,password from addresser t where t.isused=?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, Constants.ISUSED_0);
			rs = ps.executeQuery();
			Map<String,String> map = null;
			while(rs.next()){
				map = new HashMap<String,String>();
				map.put("mailurl",rs.getString("mailurl"));
				map.put("mailaddr",rs.getString("mailaddr"));
				map.put("password",rs.getString("password"));
				rvt.add(map);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			closeObject(conn, ps, rs);
		}
		return rvt;
	}
	
	public Map<String,String> findAddresser(String mailUrl){
		Map<String,String> rvt = new HashMap<String,String>();
		Connection conn = getConnection();
		String sql = "select mailurl,mailaddr,password from addresser t where t.isused=? and mailurl=?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, Constants.ISUSED_0);
			ps.setString(2, mailUrl);
			rs = ps.executeQuery();
			if(rs.next()){
				rvt.put("mailurl",rs.getString("mailurl"));
				rvt.put("mailaddr",rs.getString("mailaddr"));
				rvt.put("password",rs.getString("password"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			closeObject(conn, ps, rs);
		}
		return rvt;
	}
	
	/**
	 * 获得收人件串
	 * @return
	 */
	public List<String> getAddressee(){
		List<String> list = findAddressee();
		List<String> rvt = new ArrayList<String>();
		StringBuffer str = new StringBuffer();
		int count = 0;
		for(String email : list){
			str.append(email).append(";");
			count ++;
			if(count % MailUtils.getAddresseeNum() == 0){
				rvt.add(str.toString());
				str.delete(0, str.length());
			}
			
		}
		if(count != 0 && count % MailUtils.getAddresseeNum() != 0){
			rvt.add(str.toString());
		}
		return rvt;	
	}
	
	/**
	 * 关闭所有的数据操作相关的对象
	 * @param conn
	 * @param ps
	 * @param rs
	 * @return
	 */
	private boolean closeObject(Connection conn,PreparedStatement ps,ResultSet rs){
		try{
			if(rs != null){
				rs.close();
			}
			if(ps != null){
				ps.close();
			}
			if(conn != null && !conn.isClosed()){
				conn.close();
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	private static void readFile(){
		StringBuffer rvtStr = new StringBuffer();
		File file = new File("d:/25.txt");
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(file));
			String str;
			while((str = br.readLine())!=null){
				rvtStr.append(str);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String[] mails = rvtStr.toString().split(",");
		Connection conn = getConnection();
		List<String> rvt = new ArrayList();
		String sql = "insert into usermail(mail) values(?)";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			int i = 0;
			for(String mail : mails){
				ps.setString(1, mail);
				ps.addBatch();
				i ++;
				if(i % 100 == 0){
					ps.executeBatch();
				}
			}
			if(i % 100 != 0){
				ps.executeBatch();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MailHandler handler = new MailHandler();
//		handler.addAddresser("http://www.jmlib.net/mail", "ss@qq.com", "password");
//		handler.findAddresser();
//		handler.updateIsUsed("ss@qq.com");
//		readFile();
//		handler.getToEmail();
//		getConnection();
		handler.getAddressee();
	}

}
